#include "media.h"

#include "include.h"
#include "api_fs.h"
#include "api_charset.h"

// TF卡中GPS信息
#define TF_GPS_FILE_NAME        "/t/GPS_Original_Log.csv"

static bool SaveGnssLogToTFCard(char* str)
{
    int32_t fd;
    int32_t ret;
    uint8_t *path = (uint8_t*)TF_GPS_FILE_NAME;

    fd = API_FS_Open(path, FS_O_RDWR|FS_O_APPEND | FS_O_CREAT, 0);
	if (fd < 0)
	{
		return false;
	}
    ret = API_FS_Write(fd, (uint8_t*)str, strlen(str));
    API_FS_Close(fd);
    if(ret <= 0)
        return false;
	return true;
}

// 事件处理
static void mediaEventDispatch(MediaEvent_t* pEvent)
{
    switch(pEvent->EventId)
    {
        case kMediaEventGnssData:
            SaveGnssLogToTFCard((char *)pEvent->EventData);
            break;
        default:
            break;
    }
}

void Media_TaskEntry(void *pData)
{
    MediaEvent_t* event = NULL;
    API_FS_INFO   fsInfo;
    
    MEDIA_DEBUG("TaskEntry\r\n");

    // 判断文件是否存在
    if (API_FS_GetFSInfo(FS_DEVICE_NAME_T_FLASH, &fsInfo) < 0)
        MEDIA_DEBUG("Read TF Card Info Error!\r\n");
    else
        MEDIA_DEBUG("TF Card used:%llu Bytes total:%llu Bytes",fsInfo.usedSize, fsInfo.totalSize);

    if (API_FS_GetFSInfo(FS_DEVICE_NAME_FLASH, &fsInfo) < 0)
        MEDIA_DEBUG("Read Flash Info Error!\r\n");
    else 
        MEDIA_DEBUG("Flash used:%llu Bytes:total:%llu Bytes",fsInfo.usedSize, fsInfo.totalSize);

    while (1) {
        if (OS_WaitEvent(MediaTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER)) {
            mediaEventDispatch(event);
            OS_Free(event->EventData);
            OS_Free(event);
        }
        OS_Sleep(100);
    }
}
